<?php

set_include_path(get_include_path() . PATH_SEPARATOR . "includes/php_pear/PEAR");

require_once "PEAR5.php";
require_once "HTTP/Request2.php";
require_once "Net/URL2.php";
require_once('Cache/Lite.php');

require_once "includes/Constant.php";
require_once "includes/transformer/HtmlTransformer.php";
require_once "includes/transformer/CssTransformer.php";

class WebRequest
{
	private $request;

	private $response;

	private $urlString;

	private $url;

	private $content;
	private $contentCached;

	private $cache;

	public function __construct($url = null)
	{
		$this->urlString = $url;
		$this->url = new Net_URL2($this->urlString);
		$this->request = new HTTP_Request2($this->url);
		$this->request->setHeader('user-agent', Constant::$USER_AGENT);

		$this->cache = new Cache_Lite(array(
		    'cacheDir' => '/tmp/',
		    'lifeTime' => 7200,
		    'pearErrorMode' => CACHE_LITE_ERROR_DIE  
				));

	}

	public function isCached(){
		$this->contentCached = $this->cache->get($this->urlString);
		if($this->contentCached == false) return false;
		else return true;
	}

	public function getContentCached(){
		if(!isset($this->contentCached)) $this->isCached();
		return $this->contentCached;
	}

	public function getResponse(){
		return $this->response;
	}

	public function transform()
	{
		$this->response  = $this->request->send();
		$this->content = $this->response->getBody();
			
			
		if (strlen(stristr($this->response->getHeader("content-type"),Constant::$CONTENT_TYPE_HTML))>0) {
			$htmlTransformer = new HtmlTransformer($this->url);
			$htmlTransformer->transform($this->content);

			$cssTransformer = new CssTransformer($this->url);
			$cssTransformer->transform($this->content);
		} else if (strlen(stristr($this->response->getHeader("content-type"),Constant::$CONTENT_TYPE_CSS))>0) {
			$cssTransformer = new CssTransformer($this->url);
			$cssTransformer->transform($this->content);
		} else if (strlen(stristr($this->response->getHeader("content-type"),Constant::$CONTENT_TYPE_JAVASCRIPT))>0) {
			$htmlTransformer = new HtmlTransformer($this->url);
			$htmlTransformer->transform($this->content);
		}
			
		/*
		 $base = $this->url->getScheme()."://".$this->url->getHost()."/";


		 // replace root-relative URLs
		 $this->content = preg_replace('@\<([^>]*) (href|src)="/([^"]*)"@i', '<\1 \2="' . $base . '\3"', $this->content);

		 // replace base-relative URLs (kludgy, but I couldn't get ! to work)
		 $this->content = preg_replace('@\<([^>]*) (href|src)="(([^\:"])*|([^"]*:[^/"].*))"@i', '<\1 \2="' . $base . '\3"', $this->content);


		 $this->content = preg_replace_callback(
		 '@\<([^>]*) (href|src)="([^"]*)"@i',
		 create_function(
		 '$matches',
		 'return "<".$matches[1]." ".$matches[2]."=\"d.php?u=".base64_encode($matches[3])."\"";'
		 ),
		 $this->content
		 );
		 */
			
			 	
		/*
		 /(href|src)=["\']?\/?([^>"\'\s]+)["\']?\/?/i
		 */


		/*$this->content = preg_replace_callback(
		 '/(href|src|background-image\s*:\s*url|background\s*:\s*url)\s*(=)?\s*(["\'\(])?(\/?[^>"\'\)\s]+)(["\'\)])?\/?/i',
		 array(get_class($this), 'build_url'),
		 $this->content
		 );*/



			
		//$this->content=preg_replace('#(href|src)="([^:"]*)(?:")#','$1="http://wintermute.com.au/$2"',$this->content);
			
			
		//$request = new HTTP_Request2(base64_decode($_GET["u"]));
		//$request->setHeader('Content-type: text/html; charset=utf-8');
		//$response  = $request->send();

		//header("pragma: no-cache");
		//header("cache-control: no-cache, must-revalidate");
		//echo $this->response->getHeader("content-type");
		//header('Content-type: application/pdf');
		//header("content-transfer-encoding: binary");


		//$array = $this->response->getHeader();
		//print_r($array);


		//echo $response->getBody();
		//echo "<script type=\"text/javascript\">parent.callback_IFrameLoaded();</script>";

		//echo file_get_contents(base64_decode($_GET["u"]));
			
			

	}

	public function getContent()
	{
		return $this->content;
	}

	private function build_url($matches) {
		$matchedUrl = new Net_URL2($matches[4]);
		if(!$matchedUrl->isAbsolute()){
			$matchedUrl = $this->url->resolve($matchedUrl);
		}
		return $matches[1].$matches[2].$matches[3]."d.php?u=".base64_encode($matchedUrl->getNormalizedURL()).$matches[5];
		//    	return $matches[1]."=\"d.php?u=".base64_encode($matchedUrl->getNormalizedURL())."\"";
	}

	function rewriteRelative($html, $base) {
		// generate server-only replacement for root-relative URLs
		$server = preg_replace('@^([^\:]*)://([^/*]*)(/|$).*@', '\1://\2/', $base);

		// replace root-relative URLs
		$html = preg_replace('@\<([^>]*) (href|src)="/([^"]*)"@i', '<\1 \2="' . $server . '\3"', $html);

		// replace base-relative URLs (kludgy, but I couldn't get ! to work)
		$html = preg_replace('@\<([^>]*) (href|src)="(([^\:"])*|([^"]*:[^/"].*))"@i', '<\1 \2="' . $base . '\3"', $html);

		return $html;
	}

}


?>